import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmEditableInput {

    @bindable value;
    @bindable placeholder;
    @bindable onok;
    @bindable oncancel;

    editing = false;
    oldVal;

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {

        this.blurHandler = () => {
            this.cancelHandler();
        };

        $(this.inputRef).on('blur', this.blurHandler);

        $(this.actionsRef).hover(() => {
            $(this.inputRef).off('blur', this.blurHandler);
        }, () => {
            $(this.inputRef).on('blur', this.blurHandler);
        });
    }

    editHandler() {
        this.oldVal = this.value;
        this.editing = true;
        _.defer(() => {
            $(this.inputRef).select();
        });
    }

    cancelHandler() {
        this.editing = false;
        this.value = this.oldVal;
        this.oncancel && this.oncancel();
    }

    okHandler() {
        this.editing = false;
        this.onok && this.onok(this.value);
    }

    keydownHandler() {
    	// console.log('keydownHandler');
        $(this.inputRef).off('blur', this.blurHandler);
    }

    keyupHandler() {
    	// console.log('keyupHandler');
    	this.okHandler();
        _.delay(() => $(this.inputRef).on('blur', this.blurHandler), 1000);
    }
}
